﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLULearningNetworkModel;
using DLULearningNetwork.Libs;
using DLULearningNetwork.ViewModels;
using DLULearningNetwork.ActionFilterAttributes;

namespace DLULearningNetwork.Controllers
{
    public class CourseController : FrontEndBaseController
    {
        [RequireUserLogin()]
        public ActionResult Index(int? page)
        {
            return RedirectToAction("Personal");
        }

        [RequireUserLogin()]
        public ActionResult Personal(int? page)
        {            
            if (!page.HasValue)
            {
                page = 1;
            }
            else if (page.Value < 1)
            {
                page = 1;
            }

            int totalItems = 0;
            List<Course> courses = new List<Course>();

            try
            {
                Guid categoryID;
                try
                {
                    categoryID = Guid.Parse(Request.QueryString["CategoryID"].Trim());
                }
                catch
                {
                    categoryID = Guid.Empty;
                }

                string classOwner = "";
                if (Request.QueryString["ClassOwner"].Trim() != "Tên người mở lớp")
                {
                    classOwner = Request.QueryString["ClassOwner"].Trim();
                }

                courses = Course.Paging(LoginUser.AccountID_u, categoryID, classOwner, page.Value, Constants.DEFAULT_COURSES_PERPAGE, ref totalItems);
            }
            catch
            {
                courses = Course.Paging(LoginUser.AccountID_u, page.Value, Constants.DEFAULT_COURSES_PERPAGE, ref totalItems);
            }

            return View(new ListCoursesViewModel(courses, page.Value, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult Community(int? page)
        {
            if (!page.HasValue)
            {
                page = 1;
            }
            else if (page.Value < 1)
            {
                page = 1;
            }

            int totalItems = 0;

            List<Course> courses = new List<Course>();

            try
            {
                Guid categoryID;
                try
                {
                    categoryID = Guid.Parse(Request.QueryString["CategoryID"].Trim());
                }
                catch
                {
                    categoryID = Guid.Empty;
                }

                string classOwner = "";
                if (Request.QueryString["ClassOwner"].Trim() != "Tên người mở lớp")
                {
                    classOwner = Request.QueryString["ClassOwner"].Trim();
                }

                courses = Course.Paging(page.Value, categoryID, classOwner, Constants.DEFAULT_COURSES_PERPAGE, ref totalItems);
            }
            catch
            {
                courses = Course.Paging(page.Value, Constants.DEFAULT_COURSES_PERPAGE, ref totalItems);
            }

            return View(new ListCoursesViewModel(courses, page.Value, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult Create()
        {
            Course course = new Course();
            course.StartDate_dt = DateTime.Now;
            course.EndDate_dt = DateTime.Now;
            return View(course);
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult Create(Course course, FormCollection frm)
        {
            string startDate = frm["StartDate_dt"];
            string[] startDateInfo = startDate.Split('/');
            course.StartDate_dt = new DateTime(int.Parse(startDateInfo[2]), int.Parse(startDateInfo[1]), int.Parse(startDateInfo[0]));
            string endDate = frm["EndDate_dt"];
            string[] endDateInfo = endDate.Split('/');
            course.EndDate_dt = new DateTime(int.Parse(endDateInfo[2]), int.Parse(endDateInfo[1]), int.Parse(endDateInfo[0]));         

            if (course.EndDate_dt < course.StartDate_dt)
            {
                ViewBag.CreateCourseMessage = "Ngày kết thúc phải sau ngày bắt đầu";
                return View(course);
            }

            course.CourseID_u = Guid.NewGuid();
            course.AccountID_u = LoginUser.AccountID_u;
            course.CreateDate_dt = DateTime.Now;
            course.IsRunningOnline_b = false;            

            List<string> fileIds = new List<string>();
            if (frm["files"] != null)
            {
                fileIds = frm["files"].Split(',').ToList();
            }

            List<Guid> fileIDsConverted = new List<Guid>();
            for (int i = 0; i < fileIds.Count; i++)
            {
                try
                {
                    fileIDsConverted.Add(Guid.Parse(fileIds[i]));
                }
                catch
                {
                }
            }

            if (Course.Add(course, fileIDsConverted) == 0)
            {
                ViewBag.CreateCourseMessage = "Xảy ra lỗi. Hãy thử lại";
                return View(course);
            }

            return RedirectToAction("Index");
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Wall(Guid id)
        {
            Course course = Course.GetCourseByID(id);
            if (course != null)
            {                
                return View(course);
            }
            else
            {
                LibSession.Set(Constants.ERROR_MESSAGE, "Không tồn tại khóa học này");
                return RedirectToAction("Error");
            }
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]        
        public ActionResult Details(Guid id)
        {
            Course course = Course.GetCourseByID(id);
            Account currentUser = RequireUserLogin.LoginUser;
            Enrollment enrollment = Enrollment.Single(currentUser.AccountID_u, course.CourseID_u);
            if (enrollment != null || course.AccountID_u == currentUser.AccountID_u)
            {
                ViewBag.ShowPostBox = true;
            }
            else
            {
                ViewBag.ShowPostBox = false;
            }
            if (course != null)
            {
                return PartialView(course);
            }
            else
            {
                LibSession.Set(Constants.ERROR_MESSAGE, "Không tồn tại khóa học này");
                return RedirectToAction("Error");
            }
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserJoinClass(ErrorMessage = "Bạn không phải là thành viên của khóa học này")]
        [RequireUserLogin()]
        public ActionResult ClassRoom(Guid id)
        {
            Course entity = Course.GetCourseByID(id);
            if (entity != null)
            {
                if (LoginUser.AccountID_u != entity.AccountID_u)
                {
                    if (!entity.IsRunningOnline_b)
                    {
                        LibSession.Set(Constants.ERROR_MESSAGE, "Lớp học chưa được khởi động");
                        return RedirectToAction("Error");
                    }
                }

                SeminarSchedule seminarSchedule = SeminarSchedule.SelectByCourseID(entity.CourseID_u, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                if (seminarSchedule != null)
                {
                    List<ScheduleTime> scheduleTimes = ScheduleTime.SelectBySeminarScheduleID(seminarSchedule.SeminarScheduleID_u);
                    for (int i = 0; i < scheduleTimes.Count; i++)
                    {
                        TimeSpan now = DateTime.Now.TimeOfDay;
                        if (scheduleTimes[i].Start_t <= now && scheduleTimes[i].End_t >= now)
                        {
                            return View(id);
                        }
                    }
                }

                LibSession.Set(Constants.ERROR_MESSAGE, "Hiện tại chưa tới giờ học của lớp này");
                return RedirectToAction("Error");
            }
            else
            {
                LibSession.Set(Constants.ERROR_MESSAGE, "Không tồn tại khóa học này");
                return RedirectToAction("Error");
            }
        }

        [RequireUserLogin()]
        [HttpPost]
        public string Enrol(Guid courseID)
        {
            if (Enrollment.Single(LoginUser.AccountID_u, courseID) == null)
            {
                Enrollment enrollment = new Enrollment();
                enrollment.EnrollmentID_u = Guid.NewGuid();
                enrollment.AccountID_u = LoginUser.AccountID_u;
                enrollment.CourseID_u = courseID;
                enrollment.Status_i = 0; // waiting
                enrollment.Voted_b = false;

                if (Enrollment.Add(enrollment) == 1)
                {
                    return "";
                }
                else
                {
                    return "Có lỗi xảy ra. Hãy thử lại";
                }
            }
            else
            {
                return "Bạn đã đăng ký tham gia khóa học này rồi";
            }
        }

        [RequireUserLogin()]
        [HttpPost]
        public string AcceptOrCancelInvitation(Guid enrollmentID, bool isAccept)
        {
            Enrollment enrollment = Enrollment.Single(enrollmentID);
            if (enrollment != null)
            {
                if (isAccept)
                {
                    enrollment.Status_i = 1;
                    if (Enrollment.Update(enrollment) == 1)
                    {
                        return "";
                    }                    
                }
                else
                {
                    if (Enrollment.Delete(enrollment) == 1)
                    {
                        return "";
                    }
                }
            }

            return "Có lỗi xảy ra. Vui lòng thử lại sau";
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Renew(Guid id)
        {
            Course course = Course.GetCourseByID(id);
            if (course != null)
            {
                if (course.AccountID_u != LoginUser.AccountID_u)
                {
                    LibSession.Set(Constants.ERROR_MESSAGE, "Bạn không phải là chủ của khóa học này");
                    return RedirectToAction("Error");
                }

                return PartialView(course);
            }
            else
            {
                LibSession.Set(Constants.ERROR_MESSAGE, "Không tồn tại khóa học này");
                return RedirectToAction("Error");
            }
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult Renew(Course course, FormCollection frm)
        {
            string startDate = frm["StartDate_dt"];
            string[] startDateInfo = startDate.Split('/');
            course.StartDate_dt = new DateTime(int.Parse(startDateInfo[2]), int.Parse(startDateInfo[1]), int.Parse(startDateInfo[0]));
            string endDate = frm["EndDate_dt"];
            string[] endDateInfo = endDate.Split('/');
            course.EndDate_dt = new DateTime(int.Parse(endDateInfo[2]), int.Parse(endDateInfo[1]), int.Parse(endDateInfo[0]));

            if (Course.Renew(course) == 1)
            {
                return RedirectToAction("Wall", new { id = course.CourseID_u });
            }

            LibSession.Set(Constants.ERROR_MESSAGE, "Có lỗi xảy ra. Hãy thử lạia");
            return RedirectToAction("Error");
        }

        #region MEMBER

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Members(Guid id)
        {
            List<Enrollment> enrollments = Enrollment.SelectByCourseID(id);
            return PartialView(new CourseMembersViewModel(id, enrollments));
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult ChangeEnrollmentStatus(string enrollmentIDs, int status)
        {
            List<string> lstEnrollmentIDs = enrollmentIDs.Split('|').ToList();
            Guid courseID = Guid.Empty;
            for (int i = 0; i < lstEnrollmentIDs.Count; i++)
            {
                try
                {
                    Guid enrollmentID = Guid.Parse(lstEnrollmentIDs[i]);
                    Enrollment enrollment = Enrollment.Single(enrollmentID);
                    if (enrollment != null)
                    {
                        if (courseID == Guid.Empty)
                        {
                            courseID = enrollment.CourseID_u;
                        }

                        if (enrollment.Status_i != status)
                        {
                            enrollment.Status_i = status;
                            Enrollment.Update(enrollment);
                        }
                    }
                }
                catch
                { }
            }

            return RedirectToAction("Members", new { id = courseID });
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Invite(Guid courseID)
        {
            List<Account> accounts = Account.SelectAccountIsFriendAndNotEnrollCourseYet(LoginUser.AccountID_u, courseID);
            return PartialView(accounts);
        }

        [RequireUserLogin()]
        [HttpPost]
        public void Invite(Guid courseID, string accountIDs)
        {
            List<string> accountIDsSplitted = accountIDs.Split(',').ToList();
            List<Guid> accountIDsConverted = new List<Guid>();
            for (int i = 0; i < accountIDsSplitted.Count; i++)
            {
                try
                {
                    accountIDsConverted.Add(Guid.Parse(accountIDsSplitted[i]));
                }
                catch { }
            }

            List<Enrollment> enrollments = new List<Enrollment>();
            for (int i = 0; i < accountIDsConverted.Count; i++)
            {
                Enrollment entity = new Enrollment();
                entity.EnrollmentID_u = Guid.NewGuid();
                entity.AccountID_u = accountIDsConverted[i];
                entity.CourseID_u = courseID;
                entity.Status_i = 3;
                entity.Voted_b = false;
                enrollments.Add(entity);
            }

            Enrollment.Add(enrollments);
        }
        #endregion

        #region SCHEDULE

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Schedule(Guid id, int? year, int? month)
        {
            ScheduleViewModel scheduleViewModel = null;
            if (!year.HasValue || !month.HasValue)
            {
                scheduleViewModel = new ScheduleViewModel(id, DateTime.Now.Year, DateTime.Now.Month);
            }
            else
            {
                scheduleViewModel = new ScheduleViewModel(id, year.Value, month.Value);
            }

            return PartialView(scheduleViewModel);
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult EditSeminarSchedule(Guid id, int? year, int? month, int? day)
        {
            if (!year.HasValue)
                year = DateTime.Now.Year;
            if (!month.HasValue)
                month = DateTime.Now.Month;
            if (!day.HasValue)
                day = DateTime.Now.Day;

            SeminarSchedule sc = SeminarSchedule.SelectByCourseID(id, year.Value, month.Value, day.Value);
            if (sc == null)
            {
                sc = new SeminarSchedule();
                sc.SeminarScheduleID_u = Guid.NewGuid();
                sc.Date_dt = new DateTime(year.Value, month.Value, day.Value);
                sc.CourseID_u = id;
                sc.Description_s = "";
                SeminarSchedule.Add(sc);
            }

            return PartialView("EditSchedule", sc);
        }

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult ReloadSeminarScheduleAfterEdit(Guid id, int? year, int? month, int? day)
        {
            if (!year.HasValue)
                year = DateTime.Now.Year;
            if (!month.HasValue)
                month = DateTime.Now.Month;
            if (!day.HasValue)
                day = DateTime.Now.Day;

            SeminarSchedule sc = SeminarSchedule.SelectByCourseID(id, year.Value, month.Value, day.Value);
            if (sc.ScheduleTimes.Count <= 0)
            {
                SeminarSchedule.Delete(sc);
            }

            ScheduleViewModel scheduleViewModel = new ScheduleViewModel(id, year.Value, month.Value);
            return PartialView("Schedule", scheduleViewModel);
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult CreateScheduleTime(Guid seminarScheduleID, int startHour, int startMinute, int endHour, int endMinute, string description)
        {
            SeminarSchedule sc = SeminarSchedule.SelectByID(seminarScheduleID);
            if (sc != null)
            {
                ScheduleTime scheduleTime = new ScheduleTime();
                scheduleTime.ID_u = Guid.NewGuid();
                scheduleTime.SeminarScheduleID_u = seminarScheduleID;
                scheduleTime.Start_t = new TimeSpan(startHour, startMinute, 0);
                scheduleTime.End_t = new TimeSpan(endHour, endMinute, 0);
                scheduleTime.Description_s = description;
                if (ScheduleTime.Add(scheduleTime) != 1)
                {
                    ViewBag.CreateScheduleTimeMessage = "Có lỗi xảy ra. Hãy thử lại";
                }
            }
            else
            {
                ViewBag.CreateScheduleTimeMessage = "Có lỗi xảy ra. Hãy thử lại";
            }

            return PartialView("EditSchedule", sc);
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult DeleteScheduleTime(Guid scheduleTimeID)
        {
            ScheduleTime st = ScheduleTime.SelectByID(scheduleTimeID);
            SeminarSchedule sc = new SeminarSchedule();
            if (st != null)
            {
                sc = SeminarSchedule.SelectByID(st.SeminarScheduleID_u);
                if (ScheduleTime.Delete(scheduleTimeID) != 1)
                {
                    ViewBag.CreateScheduleTimeMessage = "Có lỗi xảy ra. Hãy thử lại";
                }
            }
            else
            {
                ViewBag.CreateScheduleTimeMessage = "Phần tử này không tồn tại. Hãy thử lại";
            }

            return PartialView("EditSchedule", sc);
        }

        #endregion

        #region RESOURCE

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        public ActionResult Resources(Guid id)
        {
            List<CoursesFile> courseFiles = CoursesFile.SelectByCourseID(id);
            return PartialView(new CourseResourceViewModel(id, courseFiles));
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult Resources(FormCollection frmCollection)
        {
            Guid courseID = Guid.Parse(frmCollection["courseID"]);
            List<string> fileIDStrings = new List<string>();
            if (frmCollection["files"] != null)
            {
                fileIDStrings = frmCollection["files"].Split(',').ToList();
            }

            List<Guid> fileIDs = new List<Guid>();
            for (int i = 0; i < fileIDStrings.Count; i++)
            {
                try
                {
                    fileIDs.Add(Guid.Parse(fileIDStrings[i]));
                }
                catch
                {
                }
            }

            if (CoursesFile.Update(courseID, fileIDs) != 1)
            {
                ViewBag.CourseResources = "Có lỗi xảy ra. Hãy thử lại";
            }

            return RedirectToAction("Resources", new { id = courseID });
        }

        [RequireUserJoinClass(ErrorMessage = "Bạn không phải là thành viên của khóa học này")]
        [RequireUserLogin()]
        public FilePathResult Download(Guid id, Guid fileID)
        {
            DLULearningNetworkModel.File file = DLULearningNetworkModel.File.Single(fileID);

            if (file != null)
            {
                return File(file.FileSystemFolder.Path_s + "/" + file.FileName_s, "application/java-archive", file.FileName_s);
            }

            return null;
        }

        #endregion

        #region VOTE

        [CheckClassOwnerIsNotBanned]
        [RequireUserLogin()]
        [HttpPost]
        public string Vote(Guid courseID, double rate)
        {
            Enrollment enrollment = Enrollment.Single(LoginUser.AccountID_u, courseID);
            if (enrollment != null)
            {
                if (enrollment.Status_i != 1)
                {
                    return "Bạn chưa tham gia khóa học này";
                }

                if (enrollment.Voted_b)
                {
                    return "Bạn đã vote cho khóa học này rồi";
                }
                else
                {
                    if (Enrollment.Vote(enrollment, rate) == 1)
                    {
                        return "Cám ơn bạn đã vote cho khóa học này";
                    }
                    else
                    {
                        return "Có lỗi xảy ra. Hãy thử lại";
                    }
                }
            }
            else
            {
                return "Bạn chưa tham gia khóa học này";
            }
        }

        #endregion

        [RequireUserLogin()]
        public ActionResult GetPersonalFilesToChoose(int page)
        {
            if (page < 1)
            {
                page = 1;
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(LoginUser.AccountID_u, page,
                Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return PartialView("ChooseFiles_Personal", new ListFilesViewModel(files, page, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult GetCommunityFilesToChoose(int page)
        {
            if (page < 1)
            {
                page = 1;
            }

            int totalItems = 0;
            List<DLULearningNetworkModel.File> files = DLULearningNetworkModel.File.Paging(page, Constants.DEFAULT_FILES_PERPAGE, ref totalItems);
            return PartialView("ChooseFiles_Community", new ListFilesViewModel(files, page, totalItems));
        }

        [RequireUserLogin()]
        public ActionResult Error()
        {
            if (LibSession.Get(Constants.ERROR_MESSAGE) != null && LibSession.Get(Constants.ERROR_MESSAGE).ToString() != "")
            {
                ViewBag.CourseError = LibSession.Get(Constants.ERROR_MESSAGE).ToString();
                LibSession.Remove(Constants.ERROR_MESSAGE);
            }

            return View();
        }


        #region COURSE_WALL

        [RequireUserLogin()]
        public ActionResult GetListFeed(string courseID, int numberOfSkip)
        {
            //Lay cac feed co courseID người dùng yêu cầu
            Account currentUser = RequireUserLogin.LoginUser;
            Course course = Course.Single(currentUser.AccountID_u);
            if (course != null && course.AccountID_u == currentUser.AccountID_u)
            {
                ViewBag.AllowComment = true;
            }
            else
            {
                Enrollment enrollment = Enrollment.Single(currentUser.AccountID_u, Guid.Parse(courseID));
                if (enrollment != null)
                {
                    ViewBag.AllowComment = true;
                }
            }
            List<Feed> lstFeed = Feed.SelectFeedForCourseWall(Guid.Parse(courseID), numberOfSkip, Constants.DEFAULT_NUMBER_OF_FEED);
            return View("ListFeed", lstFeed);
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult AddNewPost(string courseID, string content)
        {
            if (StringHelper.GetLengthOfContent(content) < 1)
            {
                return PartialView("ErrorMessage", "unsuccess/0");
            }
            if (StringHelper.GetLengthOfContent(content) > 5000)
            {
                return PartialView("ErrorMessage", "unsuccess/1");
            }
            //Chi co ai tham gia lop hoc moi co the post len tuong lop hoc
            Account currentUser = RequireUserLogin.LoginUser;
            Enrollment enrollment = Enrollment.Single(currentUser.AccountID_u, Guid.Parse(courseID));

            if (enrollment == null || enrollment.Status_i != 1)
            {
                Course course = Course.Single(currentUser.AccountID_u);
                if (course == null)
                {
                    return PartialView("ErrorMessage", "unsuccess");
                }
            }
            //Them feed 
            Feed newFeed = new Feed();
            newFeed.FeedID_u = Guid.NewGuid();
            newFeed.ActiveAccountID_u = currentUser.AccountID_u;
            newFeed.CourseID_u = Guid.Parse(courseID);
            newFeed.Content_s = HttpUtility.HtmlDecode(content);
            newFeed.CreateDate_dt = DateTime.Now;
            newFeed.LastUpdate_dt = DateTime.Now;
            newFeed.Type_s = EnumFeedType.PostOnCourseWall.ToString();
            if (Feed.Add(newFeed) == 1)
            {
                newFeed = Feed.SelectByFeedID(newFeed.FeedID_u);// De khi bo vao view thi hok bi thieu du lieu
                if (newFeed != null)
                {
                    //Add feed cho tat ca cac thanh vien trong lop hoc
                    int i = FeedForFriend.AddFeedForCourseMember(newFeed, Guid.Parse(courseID));
                    //Add feed for friend cho nguoi mo lop hoc.
                    FeedForFriend feedForCourseOwner = new FeedForFriend();
                    feedForCourseOwner.FeedForFriendID_u = Guid.NewGuid();
                    feedForCourseOwner.FeedID_u = newFeed.FeedID_u;
                    feedForCourseOwner.AccountFriendID_u = newFeed.CourseReference.Value.AccountID_u;
                    FeedForFriend.Add(feedForCourseOwner);

                    //Tao feed hoat dong gan day post ten tuong lop hoc
                    Feed newFeedActivityPostOnCoures = new Feed();
                    newFeedActivityPostOnCoures.FeedID_u = Guid.NewGuid();
                    newFeedActivityPostOnCoures.ActiveAccountID_u = currentUser.AccountID_u;
                    newFeedActivityPostOnCoures.CourseID_u = Guid.Parse(courseID);
                    newFeedActivityPostOnCoures.Content_s = newFeed.FeedID_u.ToString() +"|"+ StringHelper.ShortcutContent(HttpUtility.HtmlDecode(content), 30);
                    newFeedActivityPostOnCoures.CreateDate_dt = DateTime.Now;
                    newFeedActivityPostOnCoures.LastUpdate_dt = DateTime.Now;
                    newFeedActivityPostOnCoures.Type_s = EnumFeedType.ActivityPostOnCourseWall.ToString();

                    //Undone : transaction
                    Feed.Add(newFeedActivityPostOnCoures);
                    // tra ve html cua feed do
                    ViewBag.AllowComment = true;
                    return PartialView("Feed", newFeed);

                }
            }


            return PartialView("ErrorMessage", "unsuccess");
        }

        [RequireUserLogin()]
        [HttpGet]
        public ActionResult GetListFeedComment(string feedID, int numberOfSkip)
        {
            List<FeedComment> lstFeedComment = FeedComment.SelectByFeedID(Guid.Parse(feedID), numberOfSkip, Constants.DEFAULT_NUMBER_OF_FEEDCOMMENT);
            lstFeedComment = lstFeedComment.OrderBy(fc => fc.CreateDate_dt).ToList();
            return PartialView("ListFeedComment", lstFeedComment);
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult AddNewComment(string courseID, string feedID, string content)
        {
            if (StringHelper.GetLengthOfContent(content) < 1)
            {
                return PartialView("ErrorMessage", "unsuccess/0");
            }
            if (StringHelper.GetLengthOfContent(content) > 5000)
            {
                return PartialView("ErrorMessage", "unsuccess/1");
            }
            //Chỉ có những người tham gia lớp học với được comment trong lớp hoc
            Feed feed = Feed.SelectByFeedID(Guid.Parse(feedID));
            Enrollment enrollment = null;
            Account currentUser = RequireUserLogin.LoginUser;
            if (feed != null)
            {
                if (feed.Type_s == EnumFeedType.PostOnCourseWall.ToString())
                {
                    if (feed.CourseReference.Value.AccountID_u != currentUser.AccountID_u)
                    {
                        enrollment = Enrollment.Single(currentUser.AccountID_u, Guid.Parse(courseID));
                        if (enrollment == null || enrollment.Status_i != 1)
                        {
                            return View("ErrorMessage", "unsuccess");
                        }
                    }

                    FeedComment fcmt = new FeedComment();
                    fcmt.ActiveAccount_u = RequireUserLogin.LoginUser.AccountID_u;
                    fcmt.FeedCommentID_u = Guid.NewGuid();
                    fcmt.Content_s = HttpUtility.HtmlDecode(content);
                    fcmt.FeedID_u = feed.FeedID_u;
                    fcmt.CreateDate_dt = DateTime.Now;
                    if (FeedComment.Add(fcmt) == 1)
                    {
                        //Undone : Transaction
                        fcmt = FeedComment.SelectByFeedCommentID(fcmt.FeedCommentID_u);
                        if (fcmt != null)
                        {
                            //Cap nhat lai lastupdate cua feed
                            Feed.UpdateLastDate(Guid.Parse(feedID));
                            Feed newFeedActivity = new Feed();
                            newFeedActivity.FeedID_u = Guid.NewGuid();
                            newFeedActivity.ActiveAccountID_u = currentUser.AccountID_u;
                            newFeedActivity.Type_s = EnumFeedType.ActivityComment.ToString();
                            newFeedActivity.CreateDate_dt = DateTime.Now;
                            newFeedActivity.LastUpdate_dt = DateTime.Now;
                            newFeedActivity.Content_s = StringHelper.ShortcutContent(content, 20);
                            newFeedActivity.CommentID = fcmt.FeedCommentID_u;
                            Feed.Add(newFeedActivity);
                            //Undone : notification for thanh vien trong lop hoc
                            return PartialView("FeedComment", fcmt);
                        }
                    }
                }
            }
            return View("ErrorMessage", "unsuccess");
        }

        [RequireUserLogin()]
        [HttpPost]
        public string DeleteFeed(string feedID)
        {
            Feed existingFeed = Feed.SelectByFeedID(Guid.Parse(feedID));
            Account currentUser = RequireUserLogin.LoginUser;
            if (existingFeed != null)
            {
                if (existingFeed.Type_s == EnumFeedType.PostOnCourseWall.ToString())
                {
                    if (existingFeed.ActiveAccountID_u == currentUser.AccountID_u
                        || existingFeed.CourseReference.Value.AccountID_u == currentUser.AccountID_u)
                    {
                        if (Feed.DeleteFeed(existingFeed.FeedID_u) == 1)
                        {
                            return "success";
                        }
                    }
                }
            }
            return "unsuccess";
        }

        [RequireUserLogin()]
        [HttpPost]
        public string DeleteFeedComment(string feedCommentID)
        {
            Account currentUser = RequireUserLogin.LoginUser;
            FeedComment fcmt = FeedComment.SelectByFeedCommentID(Guid.Parse(feedCommentID));
            if (fcmt != null)
            {
                if (fcmt.ActiveAccount_u == currentUser.AccountID_u
                    || fcmt.FeedReference.Value.ActiveAccountID_u == currentUser.AccountID_u
                    || (fcmt.FeedReference.Value.CourseReference != null
                        && fcmt.FeedReference.Value.CourseReference.Value.AccountID_u == currentUser.AccountID_u))
                {
                    if (FeedComment.Delete(fcmt.FeedCommentID_u) == 1)
                    {
                        return "success";
                    }
                }
            }
            return "unsuccess";
        }
        #endregion        
    }
}
